package com.cunzai.blog.application.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cunzai.blog.application.article.mapper.ArticleMapper;
import com.cunzai.blog.application.article.service.ArticleService;
import com.cunzai.blog.common.PO.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public Page<Article> getArticles(Long category, Long tag, int page) {
        // 使用 MyBatis-Plus 的分页插件实现分页
        Page<Article> articlePage = new Page<>(page, 10);  // 每页显示 10 条数据
        return articleMapper.selectArticlesByCategoryAndTag(articlePage, category, tag);
    }

    @Override
    public Article getArticleById(Long id) {
        // 直接调用 MyBatis-Plus 提供的 selectById 方法
        return this.getById(id);
    }

    // ArticleService.java
    public Page<Article> searchArticles(String keyword, Long category, Long tag, int page) {
        QueryWrapper<Article> query = new QueryWrapper<>();
        if (keyword != null && !keyword.isEmpty()) {
            query.lambda().like(Article::getTitle, keyword)
                    .or().like(Article::getContent, keyword);
        }
        if (category != null) {
            query.lambda().eq(Article::getCategoryId, category);
        }
        if (tag != null) {
            query.lambda().inSql(Article::getId, "SELECT article_id FROM article_tag WHERE tag_id = " + tag);
        }
        return articleMapper.selectPage(new Page<>(page, 10), query);
    }
}

